package cn.yineng.java.util.string;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 关键字过滤
 * @author 		hesheng
 * @date 		Nov 26, 2010
 **/
public class KeyWordFilter {
	private static Pattern pattern = null;
	
	public KeyWordFilter() {
		StringBuilder stringBuilder = new StringBuilder();

		try {
			InputStream in = KeyWordFilter.class.getResourceAsStream("new_keyword.properties");

			Properties pro = new Properties();

			pro.load(in);

			Enumeration<?> enu = pro.propertyNames();

			while (enu.hasMoreElements()) {
				stringBuilder.append(enu.nextElement() + "|");
			}

			stringBuilder.deleteCharAt(stringBuilder.length() - 1);

			pattern = Pattern.compile(stringBuilder.toString());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public KeyWordFilter(InputStream in) {
		StringBuilder stringBuilder = new StringBuilder();

		try {
			//InputStream in = KeyWordFilter.class.getResourceAsStream("new_keyword.properties");

			Properties pro = new Properties();

			pro.load(in);

			Enumeration<?> enu = pro.propertyNames();

			while (enu.hasMoreElements()) {
				stringBuilder.append(enu.nextElement() + "|");
			}

			stringBuilder.deleteCharAt(stringBuilder.length() - 1);

			pattern = Pattern.compile(stringBuilder.toString());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public String doFilter(String str) {
		if(str == null || "".endsWith(str)){
			return str;
		}
		Matcher m = pattern.matcher(str);
		str = m.replaceAll("***");
		return str;
	}

}
